using FytSoa.Application.Crm.Param;
using FytSoa.Application.Erp;
using FytSoa.Common.Enum;
using FytSoa.Domain.Crm;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Masuit.Tools.Reflection;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace FytSoa.Application.Crm;

/// <summary>
/// 项目-发票服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v7")]
public class CrmInvoiceService : IApplicationService 
{
    private readonly SugarRepository<CrmInvoice> _thisRepository;
    private readonly ErpFlowUseService _flowUseService;
    private readonly CrmOperateLogService _operateLogService;
    public CrmInvoiceService(SugarRepository<CrmInvoice> thisRepository
        ,ErpFlowUseService flowUseService
        ,CrmOperateLogService operateLogService)
    {
        _thisRepository = thisRepository;
        _flowUseService = flowUseService;
        _operateLogService = operateLogService;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<CrmInvoiceDto>> GetPagesAsync(CrmInvoiceSearchParam param)
    {
        var query = await _thisRepository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Number.Contains(param.Key))
            .WhereIF(param.PaymentId!=0,m=>SqlFunc.ToString(m.PaymentId).Contains(param.PaymentId.ToString()))
            .WhereIF(param.ContractId!=0,m=>m.ContractId==param.ContractId)
            .Includes(m=>m.Customer)
            .Includes(m=>m.Contract)
            .Includes(m=>m.Employee)
            .Includes(m=>m.TypeCode)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        var result=query.Adapt<PageResult<CrmInvoiceDto>>();
        if (result.Items.Count==0)
        {
            return result;
        }

        var paymentIds = new List<long>();
        var paymentListIds = result.Items.Select(m => m.PaymentId);
        foreach (var item in paymentListIds)
        {
            paymentIds.AddRange(item);
        }

        paymentIds = paymentIds.Distinct().ToList();
        var paymentRepository = _thisRepository.ChangeRepository<SugarRepository<CrmPayment>>();
        var list = await paymentRepository.GetListAsync(m => paymentIds.Contains(m.Id));
        foreach (var item in result.Items)
        {
            item.Payment = new List<CrmPaymentSimpleDto>();
            foreach (var row in list)
            {
                item.Payment.Add(new CrmPaymentSimpleDto()
                {
                    Id = row.Id,
                    Number = row.Number
                });
            }
        }
        return result;
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<CrmInvoiceNewDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.Customer)
            .Includes(m=>m.Contract)
            .Includes(m=>m.Employee)
            .Includes(m=>m.TypeCode)
            .FirstAsync(m=>m.Id==id);
        var result=model.Adapt<CrmInvoiceDto>();
        if (result.PaymentId.Count >0)
        {
            result.Payment = new List<CrmPaymentSimpleDto>();
            var paymentRepository = _thisRepository.ChangeRepository<SugarRepository<CrmPayment>>();
            var list = await paymentRepository.GetListAsync(m => model.PaymentId.Contains(m.Id));
            foreach (var item in list)
            {
                result.Payment.Add(new CrmPaymentSimpleDto()
                {
                    Id = item.Id,
                    Number = item.Number
                });
            }
        }
        
        var relationRepository = _thisRepository.ChangeRepository<SugarRepository<CrmRelation>>();
        //查询关系
        var infoModel = new CrmInvoiceInfo();
        var byPostModel = new CrmBypost();
        var relationList = await relationRepository.GetListAsync(m => m.SourceId == id);
        if (relationList.Count>0)
        {
            var info = relationList.FirstOrDefault(m => m.Type == (int) CrmRelationEnum.Invoice);
            if (info!=null)
            {
                var infoRepository = _thisRepository.ChangeRepository<SugarRepository<CrmInvoiceInfo>>();
                infoModel = await infoRepository.GetFirstAsync(m => m.Id == info.RelationId);
            }
            var byPost=relationList.FirstOrDefault(m => m.Type == (int) CrmRelationEnum.ByPost);
            if (byPost!=null)
            {
                var byPostRepository = _thisRepository.ChangeRepository<SugarRepository<CrmBypost>>();
                byPostModel = await byPostRepository.GetFirstAsync(m => m.Id == byPost.RelationId);
            }
        }
        result.Flow = await _flowUseService.GetFlowAsync(model.Id);
        return new CrmInvoiceNewDto()
        {
            Invoice = result,
            Info = infoModel.Adapt<CrmInvoiceInfoDto>(),
            ByPost = byPostModel.Adapt<CrmBypostDto>()
        };
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(CrmInvoiceAddParam model)
    {
        var toDay = await _thisRepository.CountAsync(m=>SqlFunc.DateIsSame(m.CreateTime,DateTime.Now));
        model.Invoice.Number =  "FP".ResNumber(toDay);
        var invoiceId= await _thisRepository.InsertReturnSnowflakeIdAsync(model.Invoice.Adapt<CrmInvoice>());
        if (model.Invoice.FlowId!=0)
        {
            await _flowUseService.AddAsync(new ErpFlowUseDto()
            {
                FlowId=model.Invoice.FlowId,
                UseId=invoiceId,
                Type = FlowTypeEnum.Invoice,
            });
        }
        //添加发票信息
        if (!string.IsNullOrEmpty(model.Info.Header) && !string.IsNullOrEmpty(model.Info.TaxNumber))
        {
            var infoRepository = _thisRepository.ChangeRepository<SugarRepository<CrmInvoiceInfo>>();
            //判断是否存在
            var infoModel = await infoRepository.GetFirstAsync(m =>
                m.Header == model.Info.Header && m.TaxNumber == model.Info.TaxNumber);
            long infoInvoiceId;
            if (infoModel==null)
            {
                model.Info.CustomerId = model.Invoice.CustomerId;
                infoInvoiceId=await infoRepository.InsertReturnSnowflakeIdAsync(model.Info.Adapt<CrmInvoiceInfo>());
            }
            else
            {
                infoInvoiceId = infoModel.Id;
            }
            //创建关系
            var relationRepository = _thisRepository.ChangeRepository<SugarRepository<CrmRelation>>();
            await relationRepository.InsertAsync(new CrmRelation()
            {
                Type = (int)CrmRelationEnum.Invoice,
                SourceId = invoiceId,
                RelationId = infoInvoiceId
            });
        }
        
        //添加邮寄信息
        if (!string.IsNullOrEmpty(model.ByPost.AcceptName) && !string.IsNullOrEmpty(model.ByPost.Phone))
        {
            var byPostRepository = _thisRepository.ChangeRepository<SugarRepository<CrmBypost>>();
            //判断是否存在
            var byPostModel =
                await byPostRepository.GetFirstAsync(m =>
                    m.AcceptName == model.ByPost.AcceptName && m.Phone == model.ByPost.Phone);
            long byPostId;
            if (byPostModel==null)
            {
                model.ByPost.CustomerId = model.Invoice.CustomerId;
                byPostId= await byPostRepository.InsertReturnSnowflakeIdAsync(model.ByPost.Adapt<CrmBypost>());
            }
            else
            {
                byPostId = byPostModel.Id;
            }
            
            //创建关系
            var relationRepository = _thisRepository.ChangeRepository<SugarRepository<CrmRelation>>();
            await relationRepository.InsertAsync(new CrmRelation()
            {
                Type = (int)CrmRelationEnum.ByPost,
                SourceId = invoiceId,
                RelationId = byPostId
            });
        }
        
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = invoiceId,
            Type = (int)OaOperateEnum.Invoice,
            Remark = "创建了发票信息"
        });
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyAsync(CrmInvoiceAddParam model)
    {
        if (model.Invoice.Status==CrmAuditEnum.NotReviewed)
        {
            await _flowUseService.ModifyAsync(new ErpFlowUseDto()
            {
                FlowId = model.Invoice.FlowId,
                UseId = model.Invoice.Id,
                Type = FlowTypeEnum.Invoice,
            });
        }
        await _thisRepository.UpdateAsync(model.Invoice.Adapt<CrmInvoice>());
        //修改发票信息
        if (!string.IsNullOrEmpty(model.Info.Header) && !string.IsNullOrEmpty(model.Info.TaxNumber))
        {
            var infoRepository = _thisRepository.ChangeRepository<SugarRepository<CrmInvoiceInfo>>();
            await infoRepository.UpdateAsync(model.Info.Adapt<CrmInvoiceInfo>());
        }
        //修改邮寄信息
        if (!string.IsNullOrEmpty(model.ByPost.AcceptName) && !string.IsNullOrEmpty(model.ByPost.Phone))
        {
            var byPostRepository = _thisRepository.ChangeRepository<SugarRepository<CrmBypost>>();
            await byPostRepository.UpdateAsync(model.Info.Adapt<CrmBypost>());
        }
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = model.Invoice.Id,
            Type = (int)OaOperateEnum.Invoice,
            Remark = "修改了发票信息"
        });
    }
    
    /// <summary>
    /// 修改状态
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task ModifyStatusAsync(CrmContractStatusParam model)
    {
        await _thisRepository.UpdateAsync(m=>new CrmInvoice()
        {
            Status = model.Status
        },m=>model.Id.Contains(m.Id));
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateIds = model.Id,
            Type = (int)OaOperateEnum.Invoice,
            Remark = "变更了发票状态为："+model.Status.GetDescription()
        });
        if (model.Status==CrmAuditEnum.InReview)
        {
            foreach (var item in model.Id)
            {
                await _flowUseService.StartAuditAsync(item, FlowTypeEnum.Invoice);
            }
        }
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task DeleteAsync([FromBody] List<long> ids)
    {
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
        await _flowUseService.DeleteAsync(ids);
    }
}
